import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: JiuQi 玖柒
 * @Date: 2021/7/8 21:52
 * @Description:
 */
public class T350 {
    public static void main(String[] args) {
        int[] nums1 = {1, 2, 2, 2, 1};
        int[] nums2 = {2, 2};
        System.out.println(Arrays.toString(new Solution350().intersect(nums1, nums2)));
    }
}

class Solution350 {
    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> ret = new ArrayList<>();
        int index1 = 0, length1 = nums1.length;
        int index2 = 0, length2 = nums2.length;
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        while (index1 < length1 && index2 < length2) {
            if (nums1[index1] == nums2[index2]) {
                ret.add(nums1[index1]);
                index1++;
                index2++;
            } else if (nums1[index1] > nums2[index2]) {
                index2++;
            } else {
                index1++;
            }
        }
        int[] arr = new int[ret.size()];
        int index = 0;
        for (int v : ret)
            arr[index++] = v;
        return arr;
    }
}
